<?php

class ProfileController extends BaseController {

    private $imagePath = 'profile-image';

    public function index($ID) {

        $aData = array(
            'sPage_Title'       => trans('system.my-profile'),
            'sPage_Description' => trans('system.my-profile'),
            'Option'            => Cache::get('options'),
            'User'              => User::find($ID),
        );

        return View::make("profile.page", $aData);
    }

    public function getImage($ID) {

        $filePath = $this->imagePath . "/$ID.png";

        if (!File::exists($filePath)) {
            $filePath = $this->imagePath . "/no-image.png";
        }

        return Response::make(readfile($filePath), 200, array('content-type' => 'image/png'));
    }

    public function getForm($ID) {

        $aData = array(
            'Option' => Cache::get('options'),
            'User'   => User::find($ID),
        );

        return View::make("profile.update-form", $aData);
    }

    public function postForm($ID) {
        try {

            $User       = User::find($ID);
            $sFirstName = explode(" ", trim(Input::get('username')));
            $sFirstName = end($sFirstName);

            $User->saint             = Input::get('saint');
            $User->username          = Input::get('username');
            $User->firstname         = $sFirstName;
            $User->gender            = Input::get('gender');
            $User->phone             = Input::get('phone');
            $User->address           = Input::get('address');
            $User->birthday          = CNamHoa::ConvertDate(Input::get('birthday'));
            $User->baptism_date      = CNamHoa::ConvertDate(Input::get('baptism_date'));
            $User->eucharist_date    = CNamHoa::ConvertDate(Input::get('eucharist_date'));
            $User->confirmation_date = CNamHoa::ConvertDate(Input::get('confirmation_date'));
            $User->usertype          = Input::get('usertype');
            $User->usercrew          = Input::get('usercrew');
            $User->email             = Input::get('email');
            $User->parish            = Input::get('parish');
            $User->updater           = Auth::user()->id;
            $User->save();

            $aResponse = [
                "code"    => 200,
                "message" => trans('validation.custom.success-title'),
            ];
        } catch (Exception $exc) {

            $aResponse = [
                "code"    => 0,
                "message" => trans('validation.custom.error-title'),
            ];
        }

        return Response::json($aResponse);
    }

    public function getPasswordForm($ID) {

        $aData = array(
            'Option' => Cache::get('options'),
            'User'   => User::find($ID),
        );

        return View::make("profile.password-form", $aData);
    }

    public function postPasswordForm($ID) {

        if ($ID != Auth::user()->id) {
            $aResponse = [
                "code"    => 0,
                "message" => '<strong>Error!</strong> Do not have permission',
            ];
        } else {

            try {
                $User = User::find($ID);

                if (Hash::check(Input::get('password'), $User->passwd)) {
                    $User->passwd = Hash::make(Input::get('new_password'));
                    $User->save();

                    $aResponse = [
                        "code"    => 200,
                        "message" => trans('validation.custom.success-title'),
                    ];
                } else {

                    $aResponse = [
                        "code"    => 0,
                        "message" => trans('validation.custom.error-title'),
                    ];
                }
            } catch (Exception $exc) {

                $aResponse = [
                    "code"    => 0,
                    "message" => trans('validation.custom.error-title'),
                ];
            }
        }

        return Response::json($aResponse);
    }

    public function getAjaxImage($ID) {

        $aData = array(
            'Option' => Cache::get('options'),
            'User'   => User::find($ID),
        );

        return View::make("profile.image-form", $aData);
    }

    public function postAjaxImage($ID) {

        $file = Input::file('file');

        $aResponse = [
            "code"    => 0,
            "message" => trans('validation.custom.error-title'),
        ];

        if (in_array(strtolower($file->getClientOriginalExtension()), ['png', 'jpg'])) {

            $newFileName   = $ID . ".png";
            $uploadSuccess = $file->move($this->imagePath, $newFileName);

            if (is_object($uploadSuccess)) {
                $aResponse = [
                    "code"    => 200,
                    "message" => trans('validation.custom.success-title'),
                ];
            }
        }

        return Response::json($aResponse);
    }

    public function getAjaxTableDear($ID) {
        $Dears = User::find($ID)->dears()->get();
        $aData = [
            'Dears'  => $Dears,
            'Option' => Cache::get('options'),
        ];

        return View::make("profile.dear-table", $aData);
    }

    public function getAjaxCreateDear($ID) {
        $aData = [
            'ID'     => $ID,
            'url'    => route('profile-create-dear', ['id' => $ID]),
            'Dear'   => new stdClass,
            'Option' => Cache::get('options'),
        ];
        return View::make("profile.dear-new", $aData);
    }

    public function postAjaxCreateDear($ID) {

        $User = User::find($ID);

        $aResponse = [
            "code"    => 0,
            "message" => trans('validation.custom.error-title'),
        ];

        if ($User) {
            $Dear = new UserDear([
                'relationship' => Input::get('relationship'),
                'saint'        => Input::get('saint'),
                'dearname'     => Input::get('dearname'),
                'phone'        => Input::get('phone'),
                'address'      => Input::get('address'),
                'updater'      => Auth::user()->id,
            ]);

            $User->dears()->save($Dear);

            $aResponse = [
                "code"    => 200,
                "message" => trans('validation.custom.success-title'),
            ];
        }

        return Response::json($aResponse);
    }

    public function getEditDear($ID) {
        $Dear = UserDear::find($ID);

        $aData = [
            'ID'     => $Dear->user_id,
            'Dear'   => $Dear,
            'url'    => route('profile-edit-dear', ['id' => $ID]),
            'Option' => Cache::get('options'),
        ];

        return View::make("profile.dear-new", $aData);
    }

    public function postAjaxEditDear($ID) {
        $Dear = UserDear::find($ID);

        $aResponse = [
            "code"    => 0,
            "message" => trans('validation.custom.error-title'),
        ];

        if ($Dear) {

            $Dear->relationship = Input::get('relationship');
            $Dear->saint        = Input::get('saint');
            $Dear->dearname     = Input::get('dearname');
            $Dear->phone        = Input::get('phone');
            $Dear->address      = Input::get('address');
            $Dear->updater      = Auth::user()->id;
            $Dear->save();

            $aResponse = [
                "code"    => 200,
                "message" => trans('validation.custom.success-title'),
            ];
        }

        return Response::json($aResponse);
    }

    public function postAjaxRemoveDear($ID) {

        $Dear = UserDear::find($ID)->delete();

        $aResponse = [
            "code"    => 200,
            "message" => trans('validation.custom.success-title'),
        ];

        return Response::json($aResponse);
    }

    public function getAjaxTableHistory($ID) {
        $User    = User::find($ID);
        $Classes = $User->classes()->get();
        $aData   = [
            'User'    => $User,
            'Classes' => $Classes,
            'Option'  => Cache::get('options'),
        ];

        return View::make("profile.history-table", $aData);
    }

    public function getAjaxTableBrother($ID) {
        $Brothers = User::where('gencode', 'like', "%$ID%")->where('id', '<>', $ID)->get();
        $aData    = [
            'ID'       => $ID,
            'Brothers' => $Brothers,
        ];

        return View::make("profile.brother-table", $aData);
    }

    public function getAjaxCreateBrother($ID) {
        $aData = [
            'ID'      => $ID,
            'url'     => route('profile-create-brother', ['id' => $ID]),
            'Brother' => new stdClass,
        ];
        return View::make("profile.brother-new", $aData);
    }

    public function postAjaxCreateBrother($ID) {
        $Brother = User::where('gencode', 'like', "%$ID%")
            ->orWhere('gencode', 'like', "%" . Input::get('userid') . "%")
            ->orWhere('id', $ID)
            ->orWhere('id', Input::get('userid'))
            ->lists('id');

        $aResponse = [
            "code"    => 0,
            "message" => trans('validation.custom.error-title'),
        ];

        if (count($Brother) >= 2) {

            DB::table('user')->whereIn('id', $Brother)->update([
                'gencode' => implode('', $Brother),
                'updater' => Auth::user()->id,
            ]);

            $aResponse = [
                "code"    => 200,
                "message" => trans('validation.custom.success-title'),
            ];
        }

        return Response::json($aResponse);
    }

    public function postAjaxRemoveBrother($ID, $BrotherId) {

        $Brother = User::where('gencode', 'like', "%$ID%")->where('id', '<>', $BrotherId)->lists('id');

        DB::table('user')->whereIn('id', $Brother)->update([
            'gencode' => implode('', $Brother),
            'updater' => Auth::user()->id,
        ]);

        $User = User::find($BrotherId);

        if ($User) {
            $User->gencode = '';
            $User->updater = Auth::user()->id;
            $User->save();
        }

        $aResponse = [
            "code"    => 200,
            "message" => trans('validation.custom.success-title'),
        ];

        return Response::json($aResponse);
    }

}
